package com.feidee.data.report.process;

import com.alibaba.fastjson.JSONObject;
import com.feidee.data.report.exception.DataDaoException;
import com.feidee.data.report.util.DbOperationUtil;
import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class CardniuDayReport extends AProcess{
	private static Logger logger = Logger.getLogger(CardniuDayReport.class);

	@Override
	public void process(Connection conn, ProcessResult prs) throws DataDaoException{

        String sql = "select token,udid,systemname,productname,bankcode from cardniu_day_report where ymd=DATE_FORMAT(SYSDATE(),'%Y-%m-%d')";
        Statement statement = null;
        ResultSet rs = null;
        BufferedReader reader = null;
        logger.info("Run Process SQL:" + sql);
        try {
			statement = conn.createStatement();
	        rs = statement.executeQuery(sql);
	        long startTime=System.currentTimeMillis();
	        int count = 0;
	        while (rs.next()) {
	        	String token = URLEncoder.encode(rs.getString("token"),"UTF-8");
				String systemname = URLEncoder.encode(rs.getString("systemname"),"UTF-8");
				String productname = URLEncoder.encode(rs.getString("productname"),"UTF-8");
				String udid = URLEncoder.encode(rs.getString("udid"),"UTF-8");
				String bankcode = URLEncoder.encode(rs.getString("bankcode"),"UTF-8");
				//测试环境接口
				//String urlstr = "http://bbs2.feidee.net/cardniu/api/api_dailyToken.php?token="+token+"&systemname="+systemname+"&productname="+productname+"&udid="+udid+"&bankcode="+bankcode;
				//正式服接口
				String urlstr = "http://bbs.cardniu.com/cardniu/api/api_dailyToken.php?token="+token+"&systemname="+systemname+"&productname="+productname+"&udid="+udid+"&bankcode="+bankcode;
				try{
				    URL url =new URL(urlstr);
				    HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();
				    httpconn.setConnectTimeout(5000);
				    httpconn.setRequestMethod("GET");			    
				    reader = new BufferedReader(new InputStreamReader(httpconn.getInputStream(),"UTF-8"));
				    String line="";
				    StringBuffer buffer = new StringBuffer();
				    while((line = reader.readLine()) != null){
				    	buffer.append(line);
				    }
				    String result=buffer.toString();
				    System.out.println(result);
				    JSONObject reagobj = JSONObject.parseObject(result);
				    if(!reagobj.getBoolean("success")){
				    	//logger.info(urlstr+"调用返回失败，失败信息："+reagobj.getString("msg"));
				    }else{
				    	count++;
				    	//logger.info(url+"调用返回成功。");
				    }
				    if(reader != null)
				    	reader.close();
				}catch (Exception e){
					logger.info(urlstr+"调用失败："+e.getMessage());
				}

	        }
	        long endTime=System.currentTimeMillis();
			logger.info("卡牛日报数据共推送成功"+count+"条数据，花费时间： "+(endTime-startTime)+"ms");
		}catch (Exception e) {
			e.printStackTrace();
			logger.error("Run Process sql:" + sql + " Feidee reporter dao exception: " + e.getMessage(), e);
			throw new DataDaoException(e.getMessage(), e);
		}finally {
            try {
            	if(reader != null)
                	reader.close();
				DbOperationUtil.cleanConnEnv(conn , statement , rs);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        
	}

}
